/*
 * Copyright (c) 2013 - 2015, Freescale Semiconductor, Inc.
 * Copyright 2016-2017 NXP
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * o Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "app_inc.h"

/*******************************************************************************
 * Definitions
 ******************************************************************************/
#define APP_CTIMER_PULSE_COUNTER_BASE   CTIMER3

/*******************************************************************************
 * Variables
 ******************************************************************************/

volatile bool bDirForward;
volatile int32_t gCurSpeedValue;
volatile int32_t gCurSpeedValueRAW;

/*******************************************************************************
 * Prototypes
 ******************************************************************************/
void App_MeasureSpeed_Configuration(void);
int32_t App_MeasureSpeed_GetSpeed(void);
void App_NVIC_Configuration(void);

/*******************************************************************************
 * Code
 ******************************************************************************/
/*!
 * @brief Main function
 */
int main(void)
{
    int32_t counterVal;

    /* Init board hardware. */
    BOARD_InitPins();
    BOARD_BootClockRUN();

    /* Initialize debug console. */
    BOARD_InitDebugConsole(); /* Flexcomm0 - UART0, 115200. */

    PRINTF("\r\nApp_MeasureSpeed Demo.\r\n");
    PRINTF("build time: %s, %s\r\n", __TIME__, __DATE__);

    App_NVIC_Configuration();
    App_MeasureSpeed_Configuration();

    while (1)
    {
        GETCHAR();
        counterVal = App_MeasureSpeed_GetSpeed();
        //PulseCounter_ClearCounter();

        PRINTF("counterVal: %d\r\n", counterVal);
    }
}

void pint0_intr_callback(pint_pin_int_t pintr, uint32_t pmatch_status)
{

    /* 在双边沿触发模式下，不能确定是上升沿还是下降沿触发，此时在读一下触发引脚的电平就能够确定了 */
    /* 向前：PIO0_6读取低电平 */
    if (0U == ((1U << 6) & GPIO_ReadPinsInput(GPIO, 0U)) )
    {
        bDirForward = true;
    }
    else
    {
        bDirForward = false;
    }

    /* 当反转方向时，方向切换点的速度一定是0 */
    RIT_StopTimer(RIT); /* 软件在载入一个新值（包括复位定时器）之前，必须先要停止它 */
    RIT_ClearCounter(RIT); /* 清零计速计数器的值 */

    gCurSpeedValueRAW = 0;
    CTIMER_Reset(APP_CTIMER_PULSE_COUNTER_BASE); /* 清零计脉冲数的值 */
    RIT_StartTimer(RIT); /* 重新开始计速 */
}

/* RIT的中断服务程序入口 */
void RIT_IRQHandler(void)
{
    /* 启用中断自动清零计数器功能后，硬件会自动清零计数器 */
    RIT_ClearStatusFlags(RIT, kRIT_TimerFlag);

    /* 读取CTimer捕获的脉冲数，加入负号信息，得到有方向的速度 */
    gCurSpeedValueRAW = CTIMER_GetCurrentTimerCounter(APP_CTIMER_PULSE_COUNTER_BASE);
    CTIMER_Reset(APP_CTIMER_PULSE_COUNTER_BASE);
    if (bDirForward)
    {
        gCurSpeedValue = gCurSpeedValueRAW;
    }
    else
    {
        gCurSpeedValue = -gCurSpeedValueRAW;
    }
}

void App_MeasureSpeed_Configuration(void)
{
    ctimer_config_t CTimerConfigStruct;
    gpio_pin_config_t GpioPinConfigStruct;
    rit_config_t RitConfigStruct;

    /* 配置计速定时器 */
    RitConfigStruct.enableRunInDebug = false;
    RitConfigStruct.enableResetCounterOnCompare = true;
    RIT_Init(RIT, &RitConfigStruct);
    RIT_SetTimerCompare(RIT, CLOCK_GetFreq(kCLOCK_CoreSysClk) / 100U); /* 100Hz. */

    /* 使用CTimer捕捉脉冲数量 */
    /* 配置CTimer为输入捕捉模式、计数器模式 */
    CTimerConfigStruct.mode = kCTIMER_IncreaseOnFallEdge;
    CTimerConfigStruct.input = kCTIMER_Capture_0; /* 使用CAP0捕获外部脉冲 */
    CTimerConfigStruct.prescale = 0U; /* 从时钟源到计数节拍的分频因子 */
    CTIMER_Init(APP_CTIMER_PULSE_COUNTER_BASE, &CTimerConfigStruct);
    CTIMER_StartTimer(APP_CTIMER_PULSE_COUNTER_BASE);

    /* 使用引脚中断检测方向 */
    /* 初始化PINT */
    PINT_Init(PINT); /* 芯片内部就一个PINT模块，所以这里也不用定义映射了 */
    PINT_PinInterruptConfig(PINT, kPINT_PinInt0,
        kPINT_PinIntEnableBothEdges, /* 上下边沿均可触发 */
        pint0_intr_callback /* 注册触发时执行的函数 */
        );
    /* 启用GPIO模块，辅助判断边沿信息。*/
    CLOCK_EnableClock(kCLOCK_Gpio0);
    GpioPinConfigStruct.pinDirection = kGPIO_DigitalInput;
    GPIO_PinInit(GPIO, 0U, 6U, &GpioPinConfigStruct); /* PIO0_6. */
    if (0U == ((1U << 6) & GPIO_ReadPinsInput(GPIO, 0U)) )/* 向前：PIO0_6读取低电平 */
    {
        bDirForward = true;
    }
    else
    {
        bDirForward = false;
    }
    PINT_EnableCallback(PINT); /* Enable callbacks for PINT */

    /* 启动定时器定期更新速度变量 */
    RIT_StartTimer(RIT);
}

int32_t App_MeasureSpeed_GetSpeed(void)
{
    return gCurSpeedValue;
}

/* Setup the interrupts and their priority. */
void App_NVIC_Configuration(void)
{
    NVIC_EnableIRQ(RIT_IRQn);
}

/* EOF. */
